package com.xuhuan.demo.json;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xuhuan.demo.json.entity.Employee;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;

import lombok.extern.slf4j.Slf4j;
import org.junit.Before;
import org.junit.Test;

/**
 * @Author huan.xu
 * @Date 2022/10/17 19:02
 * @Description fastJSON 案例
 */
@Slf4j
public class FastJSONDemo {

    private Employee employee;

    @Before
    public void initData() {
        employee = new Employee(1, "admin", "管理员", 18);
    }

    @Test
    public void toJsonStr() {
        log.info("对象转json:{}",
                JSONObject.toJSONString(employee, SerializerFeature.WriteMapNullValue));
    }

    @Test
    public void toEmployee() {
        String jsonStr = "{\"age\":18,\"empName\":\"管理员\",\"id\":1,\"userName\":\"admin\"}";
        employee = JSON.parseObject(jsonStr, Employee.class);
        log.info("json字符串转对象：{}", employee);
    }

    @Test
    public void test() {
        String json = "[\"name1\",\"name2\"]";
        List<String> jsonList = JSONObject.parseArray(json, String.class);
        System.out.println(jsonList);
    }

    @Test
    public void test2() throws IOException {
        String path = "C:\\Users\\Administrator\\Desktop\\del-folder\\20230712-1";

        delFolder(new File(path));
    }

    private void delFolder(File file) throws IOException {
        if (file.isFile()) {
            Files.delete(file.toPath());
        } else if (file.isDirectory()) {
            File[] listFiles = file.listFiles();
            for (File childFile : listFiles) {
                delFolder(childFile);
            }
            Files.delete(file.toPath());
        }
    }
}
